import { getFourNumbers, getWinningResult } from '../../data/sortFiveUtils'
import { isSingleNumber } from '../../data/common'

const THE_ODDS = 9300 // 一注赔率（角）

/**
 * 获取本期可买注数
 * @param {*} param0 
 * @returns 
 */
const getTicketCount = ({ fourPlaceSumRange, isSamePlaceRepeatIgnore, lastTimeNumbers }) => {
  // 计数（可购买）
  let count = 0

  for (let thousand = 0; thousand < 10; thousand++) {

    // 定位去重(千位)
    if (isSamePlaceRepeatIgnore && lastTimeNumbers && thousand == lastTimeNumbers[0]) continue

    for (let hundred = 0; hundred < 10; hundred++) {

      // 定位去重(百位)
      if (isSamePlaceRepeatIgnore && lastTimeNumbers && hundred == lastTimeNumbers[1]) continue

      for (let ten = 0; ten < 10; ten++) {

        // 定位去重(十位)
        if (isSamePlaceRepeatIgnore && lastTimeNumbers && ten == lastTimeNumbers[2]) continue

        for (let one = 0; one < 10; one++) {

          // 定位去重(个位)
          if (isSamePlaceRepeatIgnore && lastTimeNumbers && one == lastTimeNumbers[3]) continue

          // 四位和值
          const fourSum = thousand + hundred + ten + one
          if (fourSum < fourPlaceSumRange[0] || fourSum > fourPlaceSumRange[1]) {
            continue
          }

          // 可以购买
          count++
        }
      }
    }
  }

  return count
}

export function getResultList({ data, fourPlaceSumRange, isSamePlaceRepeatIgnore, buyStart, buyAmount, buyMultiple }) {

  // 定义空数组，用于存储【每期】买奖信息
  const resultList = []
  // 定义空对象，用于存储【最终】买奖结果
  const resultFinal = {}

  // 定义上次开奖数字
  let lastTimeNumbers = null
  // 失败次数累加
  let failedTimes = 0
  // 本期是否购买
  let isBuy = false

  // 总购买次数
  let totalBuyTimes = 0
  // 总购未中奖数
  let totalFaildTimes = 0
  // 每轮购买次数
  let buyTimes = 0

  // 一注支出
  let aExpense = 0
  // 一次包奖支出
  let oneExpense = 0
  // 一个周期的支出
  let oneCycleExpense = 0
  // 总支出
  let totalExpense = 0

  // 一个周期的收入
  let oneCycleIncome = 0
  // 总收入
  let totalIncome = 0


  // 循环开奖号码
  const reverseDataList = [...data.list].reverse()
  reverseDataList.map((item, index) => {

    // 获取上次开奖号码
    if (index > 0) {
      lastTimeNumbers = getFourNumbers(reverseDataList[index - 1].lotteryDrawResult)
    }

    //#region filterRow处理

    // 同位重复开启并存在上次开奖号码，获取重复位的索引
    const repeatIndexArray = []
    if (isSamePlaceRepeatIgnore && lastTimeNumbers) {
      const curr = getFourNumbers(item.lotteryDrawResult)
      for (let i = 0; i < 4; i++) {
        if (curr[i] === lastTimeNumbers[i]) {
          repeatIndexArray.push(i)
        }
      }
    }

    // 添加filter对象，用于展示每条目时，控制奖球样式
    const filterRow = {
      ...item,
      filter: {
        // 四位和值的范围
        fourPlaceSumRange,
        // 同位重复的索引
        repeatIndexArray,
      }
    }
    //#endregion


    //#region  resultRow处理

    // 本期可购买注数
    const ticketCount = getTicketCount({ fourPlaceSumRange, isSamePlaceRepeatIgnore, lastTimeNumbers })

    // 添加result对象，用于展示每条目时，控制中奖结果
    const resultRow = {
      info: {}
    }

    // 购买操作（每次购买 || 杀n次后）
    isBuy = (buyStart == 0 || failedTimes >= buyStart)
    if (isBuy) {

      // 购买次数累加
      buyTimes++
      totalBuyTimes++

      if (buyMultiple == 1) {
        // 1倍
        aExpense = 1 * buyAmount
      } else if (buyMultiple == 2) {
        // 翻倍
        aExpense = Math.pow(2, buyTimes - 1) * buyAmount
      } else {
        // 盈亏
        if (buyTimes > 1) {// 本轮第N次买，计算费用
          aExpense = 0
          while (true) {
            // 1毛，2毛，3毛，4毛...
            aExpense++
            // 计算收入
            const needIncome = THE_ODDS * aExpense
            // 当收入大于本轮支出 + 本期支出，跳出循环
            if (needIncome > (oneCycleExpense + aExpense * ticketCount)) {
              break
            }
          }
        } else {
          aExpense = 1 * buyAmount // 第一次买，从1倍开始
        }
      }

      // 一次包奖费用
      oneExpense = aExpense * ticketCount
      // 本周期费用
      oneCycleExpense += oneExpense
      // 全部费用累加
      totalExpense += oneExpense

      // 记录购买次数
      resultRow.info.buyTimes = buyTimes
      // 记录本期购买注数
      resultRow.info.ticketCount = ticketCount
      // 记录本期购买单价
      resultRow.info.aExpense = aExpense
      // 记录本期费用
      resultRow.info.buyAmount = oneExpense
      // 记录周期花费      
      resultRow.info.oneCycleExpense = oneCycleExpense
    }

    // 判断是否中奖
    const winningResult = getWinningResult(filterRow)
    // 本期未中奖
    const failed = !winningResult.fourPlaceSumStatus || !winningResult.sameRepeatStatus

    if (failed) {//本期未中奖

      //失败次数累加    
      failedTimes++
      if (isBuy) {
        totalFaildTimes++
        // 记录本期中奖状态
        resultRow.info.status = 0
      }

    } else {//本期中奖

      if (isBuy) {

        // 记录本期中奖状态
        resultRow.info.status = 1

        // 计算收入
        oneCycleIncome = THE_ODDS * aExpense
        totalIncome += oneCycleIncome

        // 记录本轮收入
        resultRow.info.oneCycleIncome = oneCycleIncome
      }

      // 中奖后数据清零
      buyTimes = 0    // 购买次数归零
      failedTimes = 0 // 失败次数归零      
      oneCycleExpense = 0 // 本周期费用清零
    }

    //#endregion

    resultList.push({ ...filterRow, ...resultRow })
  })

  // 记录总结果
  resultFinal.totalBuyTimes = totalBuyTimes
  resultFinal.totalSuccessTimes = totalBuyTimes - totalFaildTimes
  resultFinal.totalFaildTimes = totalFaildTimes
  resultFinal.totalExpense = totalExpense
  resultFinal.totalIncome = totalIncome
  resultFinal.profitAndLoss = totalIncome - totalExpense

  return {
    resultList: resultList.reverse(),
    resultFinal,
  }
}

export function getWinTrend({ data, fourPlaceSumRange, isSamePlaceRepeatIgnore }) {

  const { list } = data
  const newList = [...list]
  const reverseDataList = newList.reverse()

  const oldList = []
  const oldTimes = {}
  const evenList = []
  const evenTimes = {}

  let prevType = void 0
  let oldCount = 0
  let oldTotals = 0
  let evenCount = 0
  let evenTotals = 0

  // 定义上次开奖数字
  let lastTimeNumbers = null

  reverseDataList.map((item, index) => {

    // 获取上次开奖号码
    if (index > 0) {
      lastTimeNumbers = getFourNumbers(reverseDataList[index - 1].lotteryDrawResult)
    }

    //#region filterRow处理

    // 同位重复开启并存在上次开奖号码，获取重复位的索引
    const repeatIndexArray = []
    if (isSamePlaceRepeatIgnore && lastTimeNumbers) {
      const curr = getFourNumbers(item.lotteryDrawResult)
      for (let i = 0; i < 4; i++) {
        if (curr[i] === lastTimeNumbers[i]) {
          repeatIndexArray.push(i)
        }
      }
    }

    // 添加filter对象
    const filterRow = {
      ...item,
      filter: {
        // 四位和值的范围
        fourPlaceSumRange,
        // 同位重复的索引
        repeatIndexArray,
      }
    }
    // 判断是否中奖
    const winningResult = getWinningResult(filterRow)
    // 本期未中奖
    const failed = !winningResult.fourPlaceSumStatus || !winningResult.sameRepeatStatus

    // 复用七星彩单双，单：未中奖，双：中奖
    const isSingle = failed
    if (isSingle) {
      oldCount++
      oldTotals++
    } else {
      evenCount++
      evenTotals++
    }

    if (index == 0 && !isSingle) {
      oldList.push(0)
    }

    if (prevType != void 0 && prevType != isSingle) { // 单双改变，需要存储
      if (isSingle) {
        // 本次是单数，双数记录
        evenList.push(evenCount)
        // 记录出现次数
        if (!evenTimes[evenCount]) {
          evenTimes[evenCount] = 0
        }
        evenTimes[evenCount]++

        evenCount = 0
      } else { // 本次是双数，单数记录
        oldList.push(oldCount)
        // 记录出现次数
        if (!oldTimes[oldCount]) {
          oldTimes[oldCount] = 0
        }
        oldTimes[oldCount]++

        oldCount = 0
      }
    }

    if (index == list.length - 1) {// 最后一次，需要存储
      if (oldCount > 0) {
        oldList.push(oldCount)
        // 记录出现次数
        if (!oldTimes[oldCount]) {
          oldTimes[oldCount] = 0
        }
        oldTimes[oldCount]++

        oldCount = 0
      }
      if (evenCount > 0) {
        evenList.push(evenCount)
        // 记录出现次数
        if (!evenTimes[evenCount]) {
          evenTimes[evenCount] = 0
        }
        evenTimes[evenCount]++

        evenCount = 0
      }
    }

    prevType = isSingle
  })

  return {
    count: list.length,
    startDate: list[list.length - 1].lotteryDrawTime,
    endDate: list[0].lotteryDrawTime,
    oldList,
    oldTimes,
    oldTotals,
    evenList,
    evenTimes,
    evenTotals,
    lastTimeIsSingle: prevType,
  }
}

export function getOldEvenTrend({ data, sliceNum }) {

  const { list } = data
  const newList = [...list]
  const reverseDataList = newList.reverse()

  const oldList = []
  const oldTimes = {}
  const evenList = []
  const evenTimes = {}

  let prevType = void 0
  let oldCount = 0
  let oldTotals = 0
  let evenCount = 0
  let evenTotals = 0

  reverseDataList.map((item, index) => {

    const isSingle = isSingleNumber(item, sliceNum)
    if (isSingle) {
      oldCount++
      oldTotals++
    } else {
      evenCount++
      evenTotals++
    }

    if (index == 0 && !isSingle) {
      oldList.push(0)
    }

    if (prevType != void 0 && prevType != isSingle) { // 单双改变，需要存储
      if (isSingle) {
        // 本次是单数，双数记录
        evenList.push(evenCount)
        // 记录出现次数
        if (!evenTimes[evenCount]) {
          evenTimes[evenCount] = 0
        }
        evenTimes[evenCount]++

        evenCount = 0
      } else { // 本次是双数，单数记录
        oldList.push(oldCount)
        // 记录出现次数
        if (!oldTimes[oldCount]) {
          oldTimes[oldCount] = 0
        }
        oldTimes[oldCount]++

        oldCount = 0
      }
    }

    if (index == list.length - 1) {// 最后一次，需要存储
      if (oldCount > 0) {
        oldList.push(oldCount)
        // 记录出现次数
        if (!oldTimes[oldCount]) {
          oldTimes[oldCount] = 0
        }
        oldTimes[oldCount]++

        oldCount = 0
      }
      if (evenCount > 0) {
        evenList.push(evenCount)
        // 记录出现次数
        if (!evenTimes[evenCount]) {
          evenTimes[evenCount] = 0
        }
        evenTimes[evenCount]++

        evenCount = 0
      }
    }

    prevType = isSingle
  })

  return {
    count: list.length,
    startDate: list[list.length - 1].lotteryDrawTime,
    endDate: list[0].lotteryDrawTime,
    oldList,
    oldTimes,
    oldTotals,
    evenList,
    evenTimes,
    evenTotals,
    lastTimeIsSingle: prevType,
  }
}